package com.imooc.controller;

import com.imooc.dataobject.ProductCategory;
import com.imooc.form.CategoryForm;
import com.imooc.service.CategoryService;
import com.imooc.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/seller/category")
@Slf4j
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    /**批量查找 -- 直接返回
     *
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list(Map<String, Object> map){
        List<ProductCategory> productCategoryList = categoryService.findAll();
        //  map.put("url", "/sell/seller/category/list");
        map.put("productCategoryList", productCategoryList);
        return new ModelAndView("/category/list");

    }

    /**如果传来ID -- 查找对象赋值返回前台
     * 没有传递ID值 -- 不用查找， 返回空
     * @param categoryId
     * @param map
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId", required = false) Integer categoryId,
                              Map<String, Object> map){
        ProductCategory productCategory = new ProductCategory();
        if(!StringUtils.isEmpty(categoryId)){
            productCategory = categoryService.findOne(categoryId);
        }

        map.put("productCategory", productCategory);
        return new ModelAndView("/category/index", map);
    }

    //修改 或者提交的方法在这里运行

    /**
     *
     * @param categoryForm
     * @param bindingResult
     * @param map
     * @return
     *
     * 先验证表单正确还是错误 -- 错？  返回错误页面
     *                      --  正确？进行数据的赋值，设置填充值
     *
     *  如果有ID --  查询赋值默认值
     *           --  否则新值需要单独自动生成ID 号。
     *
     *  前端数据 拷贝赋值 -- 存储，（出错处理 -- 无错直接成功 ）
     *
     */
    @PostMapping("/save")
    public ModelAndView save(@Valid CategoryForm categoryForm,
                             BindingResult bindingResult,
                             Map<String,Object> map){
        if(bindingResult.hasErrors()){
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/category/index");
            return new ModelAndView("common/error",map);
        }

        ProductCategory productCategory = new ProductCategory();

        if (StringUtils.isEmpty(categoryForm.getCategoryId())){
            //  ID是空值
            productCategory.setCategoryId(new Integer(KeyUtil.genUniqueKey()));
        }else{
            productCategory = categoryService.findOne(categoryForm.getCategoryId());
        }

        try{
            BeanUtils.copyProperties(categoryForm, productCategory);
            categoryService.save(productCategory);
        }catch (Exception e){
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/category/list");
            return new ModelAndView("common/error",map);
        }
        map.put("msg", "更改分类信息成功！");
        map.put("url", "/sell/seller/category/list");
        map.put("productCategory",productCategory);
        return new ModelAndView("common/success",map);

    }

}
